package com.mianshi;

import java.util.Scanner;

public class wangyi2 {

    static int total = Integer.MAX_VALUE;
    static String s = "";
    static int num = 0;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
//        System.out.println('b' - 'a');

        while(in.hasNext()){
             s = in.next();
             num = Integer.parseInt(in.next());
            break;
        }

        int len = s.length();
        int[] dis = new int[len-1];
        for(int i = 0; i < len-1; i++){
            dis[i] = distance(s.charAt(i),s.charAt(i+1));
        }
        int ans = len;
        if(num <= 1){
            if(num == 0){
                ans += getSum(dis);
            }
            else {
                ans += dis.length;
            }
            System.out.println(ans);
            return;
        }
        int k = (len-1) % num;
        dfs(0,0,0,len,k,dis);
        System.out.println(ans);
    }
    public static void dfs(int u, int cnt, int path, int len, int k, int[] dis){
        if(u == len - 1){
            total = Math.min(total, path);
            return;
        }
        if(cnt < k){
            dfs(u+1,cnt+1, path+dis[u], len, k,dis);
        }
        if(u+num <= len-1){
            dfs(u+num,cnt,path+num,len,k,dis);
        }
    }
    public static int getSum(int[] arr){
        int sum = 0;
        for(int item : arr){
            sum += item;
        }
        return sum;
    }
    public static int distance(char a, char b){
        if(a=='A' && b == 'Z'){
            return 1;
        }
        if(a=='Z' && b=='A'){
            return 1;
        }
        return Math.abs(a - b);
    }
}
